<template>
  <DetailsFormBox :title="page.title" :type="route.query.type" :form="data.form" :btns="[
    {
      title: '重置',
      icon: '',
      type: '',
      hidden: !isEdit,
      click: getForm,
    },
    {
      title: '保存',
      icon: '',
      type: 'primary',
      hidden: !isEdit,
      click: (form: any) => {
        saveBtn(form, false)
      },
    },
    {
      title: '保存并确认',
      icon: '',
      type: 'primary',
      hidden: !isEdit,
      click: (form: any) => {
        saveBtn(form, true)
      },
    },
  ]" :formInfo="[
    {
      label: '创建人员',
      value: 'createPersonName',
    },
    {
      label: '创建时间',
      value: 'createTime',
    },
  ]" :loading="data.loading" :loadingMsg="data.loadingMsg">
    <template #default="{ form }">
      <div class="p-12">
        <OrderInfo :produceTaskBillNo="form.produceTaskBillCode" />
        <CellBox title="基本信息" isTop>
          <FlexBox>
            <ElFormItemBox label="单据单号" prop="finishedProductStockAdjustmentNo">
              <ElInputBox :data="form" dataName="finishedProductStockAdjustmentNo" placeholder="系统自动生成" disabled />
            </ElFormItemBox>
            <ElFormItemBox label="单据备注" prop="remarks" class="wAuto">
              <ElInputBox :data="form" dataName="remarks" type="textarea" :disabled="!isEdit" />
            </ElFormItemBox>
          </FlexBox>
        </CellBox>
        <CellBox title="单据明细" isTop>
          <TableBoxMx :data="{
            disabled: !isEdit,
            tbody: form.details,
            thead: [
              {
                label: '产品名称',
                prop: 'productName',
                align: 'left',
                width: 320,
              },
              {
                label: '产品型号',
                prop: 'productSpecificationName',
                align: 'left',
                width: 160,
              },
              {
                label: '版本',
                prop: 'productVersion',
                align: 'center',
                width: 60,
              },
              {
                label: '生产批次',
                prop: 'produceTaskBillNo',
                align: 'center',
                width: 120,
              },
              {
                label: '生产日期',
                prop: 'productionDate',
                align: 'center',
                width: 120,
              },
              {
                label: '库存数量',
                prop: 'fromStockQuantity',
                align: 'center',
                width: 160,
                hidden: !isEdit,
              },
              {
                label: '原仓库',
                prop: 'fromWarehouseInfo',
                align: 'center',
                width: 160,
              },
              {
                label: '新仓库',
                prop: 'toWarehouseInfo',
                align: 'center',
                formType: 'cascader',
                formProp: 'details',
                formKey: 'toAreaSheltCode',
                dataName: ['toWareHouseAreaCode', 'toAreaSheltCode'],
                options: options.warehouse,
                width: 180,
              },
              {
                label: '调拨数量',
                prop: 'toStockQuantity',
                align: 'center',
                width: 140,
                formType: 'number',
                formProp: 'details',
                changeBtn: (value: any, row: any) => {
                  if (value > row.fromStockQuantity) {
                    proxy.$message('调拨数量不能超过库存数量', 'error');
                    row.toStockQuantity = row.fromStockQuantity
                  }
                }
              },
              {
                label: '备注',
                prop: 'remarks',
                align: 'left',
                width: null,
                formType: 'text'
              },
            ],
            operation: [
              {
                label: '删除',
                icon: 'Delete',
              }
            ],
            add: () => {
              pupAdd.state = true
              getAddTbody()
            },
          }">
          </TableBoxMx>
        </CellBox>
      </div>
    </template>
  </DetailsFormBox>
  <SelectCom :pup="pupAdd" :table="pupAdd.tableAdd" isCheckbox :selectable="(row: any) => {
    const _arr = data.form.details.map((el: any) => el.productStockNo)
    return !_arr.includes(row.productStockNo)
  }" @searchBtn="getAddTbody" @selectBtn="(arr: any) => {
    const _arr = arr.map((el: any) => ({
      ...el,
      fromProductStockNo: el.productStockNo,//原仓库
      fromWarehouseInfo: el.warehouseInfo,//原仓库
      fromStockQuantity: el.stockQuantity,//原库存数量
    }))
    data.form.details.push(..._arr)
  }">
  </SelectCom>
</template>
<script setup lang="ts">
import { sendMsg } from '@/utils/crossTagMag.ts';
import { useListComponent } from '../pageTs.ts'; // 引入逻辑
const { dataInfo, options } = useListComponent();
import page from '../page.ts'; // 引入逻辑
import '../pageCss.scss'; // 引入样式
const { proxy } = getCurrentInstance() as any;
const data: any = reactive({
  loading: false,
  loadingMsg: '',
  mainPage: 1,
  form: {
    finishedProductStockAdjustmentCode: '', // 唯一code
    remarks: '', // 备注说明
    details: []
  },
});
const isEdit = ref(true)
//获取成品信息
const getAddTbody = () => {
  const _table = pupAdd.tableAdd
  _table.loading = true
  proxy.$api.FinishedProduct.GetFinishedProductStockDetailPageList({
    ..._table.search,
  })
    .then((res: any) => {
      _table.tbody = res.list
      _table.search.totalCount = res.totalCount;
      _table.loading = false
    })
    .catch(() => {
      _table.loading = false
    });
}
const pupAdd: any = reactive({
  state: false,
  typeName: 0,
  title: `选择成品`,
  tbody: [],
  tableAdd: {
    rowKey: 'productStockNo',
    search: {
      pageIndex: 1, //当前页码
      pageSize: 30, //每页显示数据的数量
      totalCount: 0, //总数量
      queryDataBaseFiled: '', // 关键字查询字段，空值查询全部
      likeWords: '', // 查询关键字，空值查询全部
      onlySelf: 0, // 是否只查询自己创建的，0：查所有、1：只查自己创建的
      isShowDisabled: -1, // 是否显示禁用,-1：显示所有的；0：仅显示未作废的；1 仅显示作废的
      orderByFiled: '', // 排序字段
      orderByType: 1, // 排序方式，0-倒序,1-升序
      beginTime: '', // 生产日期范围-开始时间
      endTime: '', // 生产日期范围-结束时间
      //
      endProductionDate: '', //最后生产批次日期
      onlyStocked: 1//仅查看有库存，-1 查全部、0-仅查库存数量为0的、1-仅查库存数量大于0的
    },
    tbody: [],
    thead: [
      {
        label: '成品名称',
        prop: 'productName',
        align: 'left',
        width: null,
        isCanSearch: true
      },
      {
        label: '型号规格',
        prop: 'productSpecificationName',
        align: 'left',
        width: 220,
      },
      {
        label: '产品版本',
        prop: 'productVersion',
        align: 'center',
        width: 160,
      },
      {
        label: '客户名称',
        prop: 'customerName',
        align: 'center',
        width: 220,
        isCanSearch: true
      },
      {
        label: '协议书号',
        prop: 'xieYiShuHao',
        align: 'center',
        width: 160,
        isCanSearch: true
      },
      {
        label: '生产批次',
        prop: 'produceTaskBillNo',
        align: 'center',
        width: 160,
        isCanSearch: true
      },
      {
        label: '生产日期',
        prop: 'productionDate',
        align: 'center',
        width: 140,
        isCanSearch: true
      },
      {
        label: '库区库位',
        prop: 'warehouseInfo',
        align: 'center',
        width: 180,
        isCanSearch: true
      },
      {
        label: '库存数量',
        prop: 'stockQuantity',
        align: 'center',
        width: 140,
      },
    ],
  },
});
import { useRoute } from 'vue-router';
// 获取当前路由对象
const route = useRoute();
//获取数据
const getForm = async () => {
  const _query: any = route.query
  setLoading()
  //是否新建
  if (!!!_query.code) {
    data.loading = false
    return
  }
  proxy.$api.FinishedProductStockAdjustment.GetFinishedProductStockAdjustment({
    code: _query.code,
  })
    .then((res: any) => {
      proxy.$message('获取成功')
      isEdit.value = ['1', '2'].includes(_query.type)
      data.form = res
      data.loading = false
    })
    .catch(() => {
      data.loading = false
    });
};
const saveBtn = (form: any, isConfirm: boolean = false, isPartial?: number) => {
  const _form: any = {
    finishedProductStockAdjustmentCode: form.finishedProductStockAdjustmentCode, // 成品报废单唯一code
    remarks: form.remarks, // 备注说明
    details: form.details.map((el: any) => (
      {
        fromProductStockNo: el.fromProductStockNo, // 旧-库存唯一code
        toWareHouseAreaCode: el.toWareHouseAreaCode, // 新-库区code
        toAreaSheltCode: el.toAreaSheltCode, //新-库位code
        toStockQuantity: el.toStockQuantity, //调库数量（调库数量不能大于库存数量）
        remarks: el.remarks, //备注
      }
    ))
  }
  // return
  switch (route.query.type) {
    case '1'://新建
      proxy.$api.FinishedProductStockAdjustment.AddFinishedProductStockAdjustment(_form)
        .then((res: any) => {
          if (isConfirm) {
            _setState(res)
          } else {
            _sun()
          }
        })
        .catch(() => { });
      break;
    case '2'://编辑
      proxy.$api.FinishedProductStockAdjustment.UpdateFinishedProductStockAdjustment(_form)
        .then((res: any) => {
          if (isConfirm) {
            _setState(_form)
          } else {
            _sun()
          }
        })
        .catch(() => { });
      break;
    default:
      break;
  }
  function _sun() {
    closeBtn('保存成功')
  }
  function _setState(row: any) {
    proxy.$api.FinishedProductStockAdjustment.ConfirmFinishedProductStockAdjustment({
      code: row.finishedProductStockAdjustmentCode, //
    })
      .then((res: any) => {
        _sun()
      })
      .catch(() => {
        _sun()
      });
  }
};
const closeBtn = (message?: string) => {
  if (message) {
    proxy.$message(message)
  }
  sendMsg('save', true);
  // getForm()
  window.close();
};
const setLoading = (title: string = '正在获取数据,请稍等...') => {
  if (!data.loading) {
    data.loading = true;
    data.loadingMsg = title;
  }
};
import { getWarehouse } from '@/utils/optionsArr.ts';
onMounted(() => {
  getForm();
  getWarehouse(options, 'warehouse')//获取仓库
});
</script>
